package com.ztmg.common.util;



import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;

public class RSAFromPkcs8 {

    private static final String priKey = "MIICXAIBAAKBgQDCRloa+hgeoulAfNwXSD45U0z77gBe59Jtvf6bX2pJuCg5CO1r"
            +"4DRtoatNaNCupxX9+CwPjcaJ6aEgaHpEWkYz0lTAf7m22ipmbWG5FK7ToqVTnkAK"
            +"EtBYQrgTQpx0MaXXebPwFS28R/K6npD8B2UjWpesmv5kbkr3L8hd7ypnnwIDAQAB"
            +"AoGAc55g46sxjZIQ1SM57NU+yukLaOd06wZ2Un9/NkKrw+HIdmEcw1W0fgZ4J2KY"
            + "x0iDKxl2R29t2Aflr57eHS3IluU79uDsFUXWXkUEctEBqb4CEguppRJwrqT52I4I"
            +"018dD/Ju5jJEPjGEr4ealWeTakjI5jR3sUx7q8xunJutiFECQQD8ZCe2M0EQPiqG"
            +"NeL2LqLkccqg1cC2yNhVvkQlG0yAa/YSuyaNkfeb7ac0PviTkAYwIWmnqVU4Ka7f"
            +"xp2fLGwHAkEAxQ14J1vSWw818NQA4MRXhdqjLIEkizC7Tw1slVO5yQXZtoe7T9dc"
            +"2bxvqi71DrVTzMj7jJ6DoPqgqhiZTZhxqQJAQAxOg48YKL4N3ocYNG77SUuTJyN3"
            +"RytKst+YvW3jCQfcpz4092IeWsSBVOHSBOhcmaQxAqoXBSyWwxTM9RK5ywJAQWiZ"
            + "K6dlCejgpNIagIFr8/iBFXLAqJtCcZkpI+Ao2Tth6x7e5D++iF/uSPVRTtKNwHou"
            +"VZ0AYF0RG6USrhkeEQJBAO5fVSJ7ZvGumOAnRnJgX3DrmmwvSPeq5KEPUsx4fUvl"
            + "SXNQgs4VZ/Pit6xllSoiHWLR3k/g0NR6TY56l+dIvaI=";
    public static String getSignString(String data) throws Exception
    {
        //获取KeyFactory，指定RSA算法

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        //将BASE64编码的私钥字符串进行解码

        BASE64Decoder decoder = new BASE64Decoder();

        byte[] encodeByte = decoder.decodeBuffer(priKey);

//将BASE64解码后的字节数组，构造成PKCS8EncodedKeySpec对象，生成私钥对象

        PrivateKey privatekey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodeByte));



        //b）使用私钥，对数据进行签名

            //获取Signature实例，指定签名算法（本例使用SHA1WithRSA）

            Signature signature = Signature.getInstance("SHA1WithRSA");

//加载私钥

        signature.initSign(privatekey);

//更新待签名的数据

        signature.update(data.getBytes("UTF-8"));

//进行签名

        byte[] signed = signature.sign();

//将加密后的字节数组，转换成BASE64编码的字符串，作为最终的签名数据

        BASE64Encoder encoder = new BASE64Encoder();

        return encoder.encode(signed);

    }

}
